package com.project.dao.impl;

import com.project.bean.UserBean;
import com.project.dao.UserDao;

import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl extends BaseDao implements UserDao {
    /**
     * 登陆
     * @param userName  用户名
     * @param pwd 密码
     * @return
     */
    @Override
    public UserBean lang(String userName, String pwd) {
        UserBean user = null;
//        链接
        this.setConnection();
        try {
//            执行sql语句
            ps=con.prepareStatement("select * from t_users where u_name=? and u_password=?");
//            占位符
            ps.setObject(1,userName);
            ps.setObject(2,pwd);
//            结果集
            res=ps.executeQuery();
//            循环加入
            if (res.next()){
                user=new UserBean();
                user.setId(res.getInt("pk_usersId"));
                user.setUserName(res.getString("u_name"));
                user.setPassword(res.getString("u_password"));
            }
//            关闭流
            this.closeConnection();

        } catch (Exception e) {
            e.printStackTrace();
        }
            return user;
    }

    /**
     * 注册
     * @param user 用户对象
     */
    @Override
    public void add(UserBean user) {
       this.setConnection();
        try {
            ps = con.prepareStatement("insert into t_users(u_name,u_password,u_money,u_date,u_phone)"+" values(?,?,?,?,?)");
            ps.setObject(1,user.getUserName());
            ps.setObject(2,user.getPassword());
            ps.setObject(3,user.getMoney());
            ps.setObject(4,user.getBirthday());
            ps.setObject(5,user.getIphone());
            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            this.closeConnection();
        }

    }

    @Override
    public List<UserBean> findAll() {
        this.setConnection();
        List<UserBean> list = new ArrayList<>();

        try {
            ps = con.prepareStatement("select * from t_users");
            res=ps.executeQuery();
            while (res.next()){
                UserBean user = new UserBean();
                list.add(this.getUser());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public static void main(String[] args) {
        UserDao dao = new UserDaoImpl();
//        dao.add(new UserBean("陈","123456",5000,LocalDate.parse("1997-05-03"),"18402287987"));
//
//        UserBean user=dao.lang("li","11");
//        if (user==null){
//            System.out.println(1);
//        }
    }


}
